<?php
/**
 * YImage
 * 图片缩略图和水印生成
 * @uses
 * Yii::import('application.extensions.helper.YImage');
 * $thumbnail_file_name = YImage::generateThumbnail("object", file_name);
 * 
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */
class YImage extends CApplicationComponent {
    
    /**
     * get thumbnail width and height value
     * @param string $object
     * @return array about thumbnail width and height value
     */
    protected static function getThumbnailWidthHeight($object) {
        $config = Yii::app()->params['upload'];
        $width = isset($config["thumbnail_{$object}_width"])
            ? $config["thumbnail_{$object}_width"]
            : 200;
        $height = isset($config["thumbnail_{$object}_height"])
            ? $config["thumbnail_{$object}_height"]
            : 200;
        return array('width' => $width, 'height' => $height);
    }

    /**
     * 通用图片缩略图生成
     * @param <string> $source_file
     * @param <integer> $width
     * @param <integer> $height
     * @return string Thumbnail name
     */
    public static function generateThumbnail($object, $file_name) {
        ini_set("memory_limit", "-1");
        set_time_limit(0);
        Yii::import('application.extensions.phpthumb.EasyPhpThumb');
        $thumb = new EasyPhpThumb();
        $thumb->init();
        $thumb_directory = "/upload/{$object}";
        $thumb_saved_path = Yii::getPathOfAlias('webroot') . "/upload/{$object}/";

        $thumb->setThumbsDirectory($thumb_directory);
        $wh = self::getThumbnailWidthHeight($object);
        $width = $wh['width'];
        $height = $wh['height'];
        try {
            $thumb_file_name = explode('.', $file_name);

            $thumb->load($thumb_saved_path . $file_name)
                ->resize($width, $height)
                ->save("{$thumb_file_name[0]}_thumb" . ".{$thumb_file_name[1]}");
            return "{$thumb_file_name[0]}_thumb" . ".{$thumb_file_name[1]}";
        } catch (Exception $ex) {
            echo $ex;
            exit;
            return '';
        }
    }
}
